<?php

namespace App\V3\V3_2_7\Controllers;

use App\V3\V3_2_7\Models\BarterModel;
use App\V3\V3_2_7\Models\MaterielModel;
use App\V3\V3_2_7\Models\OverflowBreakagePackageModel;
use App\V3\V3_2_7\Models\SalesReturnModel;
use App\V3\V3_2_7\Models\SellModel;
use App\V3\V3_2_7\Services\CheckService;
use App\V3\V3_2_7\Services\StorageManageService;
use App\V3\V3_2_7\Models\CheckModel;
use App\V3\V3_2_7\Models\OverflowBreakageChecksModel;
use App\V3\V3_2_7\Models\OverflowBreakageDetailModel;
use App\V3\V3_2_7\Models\OverflowBreakageModel;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;

class CheckController extends BaseController
{
    public function agreeOrRefund(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'id' =>'required|integer',//审批主键id
            'all_id' =>'required|integer',//关联id
            'status' =>'required|string',//审批状态：0-拒绝 1-同意
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        $data['main_id'] = $this->getMainUserId();
        $data['user_id'] = $this->getUserId();
        $data['batch_title'] = $this->batchTitle();
        $data['is_use_shelf'] = $this->isUseShelf();
        $data['out_way'] = $this->getOutWay();

        if($data['status']) {
            $result = CheckService::agree($data);
            $logData = '已同意!';
        } else {
            $result = CheckService::refuse($data);
            $logData = '已拒绝!';
        }
        $this->log('审批', $data, $logData);
        return response()->json($result);
    }

    /**
     * 审批列表
     * change 在 2021/11/9 16:32 创建
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'pageSize' =>'required|integer',//页面大小
            'currentPage' =>'required|integer',//当前页
            'type'=>'required|integer'//类型：0-报溢报损 1-销售采购
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        if($data['type']==CheckModel::$_TYPE_0){
            $type = [0,1];
        }elseif($data['type']==CheckModel::$_TYPE_1){
            $type = [2,3];
        }elseif($data['type']==CheckModel::$_TYPE_2){
            $type = [4];
        }

        $data['check_status'] = isset($data['check_status'])?[$data['check_status']]:CheckModel::$_TYPE_LIST;
        $keyword = isset($data['keyword'])?$data['keyword']:'';
        if($this->getMainUserId() == $this->getUserId()){//超管
            $condition['a.main_id'] = $this->getMainUserId();
        }else{
            $condition['d.admin_id'] = $this->getUserId();
        }
        if($data['type']==0){//报溢报损
            $model = CheckModel::select(
                'a.*',
                'b.username',
                'c.overflow_breakage_no',
                'c.status  as check_status'
            )->from('check as a')
            ->leftJoin('admin as b','a.user_id', '=','b.id')
            ->leftJoin('overflow_breakage as c','a.all_id', '=','c.id')
            ->leftJoin('overflow_breakage_check as d','d.o_b_main_id', '=','c.id')
            ->where(function($query) use($keyword){
                if(!empty($keyword)){
                    $query->orWhere('a.order_no','%'.$keyword.'%');
                    $query->orWhere('b.username','%'.$keyword.'%');
                }
            })
            ->whereIn('c.status',$data['check_status'])
            /*->where('a.status',0)*/
            ->whereIn('a.type',$type);
           /* if($this->getMainUserId() != $this->getUserId()){
                $model->whereRaw("FIND_IN_SET(".$this->getUserId().",`check_person`)");
                $model->whereRaw("FIND_IN_SET(".$this->getUserId().",`check_person_tmp`)");
            }*/
            $model = $model->orderBy('a.id','desc')
            ->where([
                'a.repeal_status' => 0,
                'c.delete_flag' => 0,
                ])
            ->where($condition)
            ->paginate($data['pageSize'],['*'], '',$data['currentPage']);

        }elseif(in_array($data['type'],[1,2])){//销售采购退换货

            $model = CheckModel::select('a.*','b.username')
            ->from('check as a')
            ->leftJoin('admin as b','a.user_id', '=','b.id')
            ->where('type','!=',5)
            ->where(function($query) use($keyword){
                if(!empty($keyword)){
                    $query->orWhere('a.order_no','like','%'.$keyword.'%');
                    $query->orWhere('b.username','like','%'.$keyword.'%');
                }
            })
            ->whereIn('type',$type);
          /*  if($this->getMainUserId() != $this->getUserId()){
                $model->whereRaw("FIND_IN_SET(".$this->getUserId().",`check_person`)");
                $model->whereRaw("FIND_IN_SET(".$this->getUserId().",`check_person_tmp`)");
            }*/
            $model = $model->whereIn('a.eudit_status',$data['check_status'])
            ->where('a.repeal_status',0)
            ->where($condition)
            ->where('a.created_at','>','1713506400')
            ->orderBy('a.id','desc')
            ->paginate($data['pageSize'],['*'], '',$data['currentPage'])->toArray();
            if(!empty($model['data'])){
                foreach ($model['data'] as &$val){
                    if($val['type'] ==2){
                        $info = SellModel::select(
                            'out_status',
                            'pay_status',
                            'final_money',
                            'other_charges',
                            'real_money',
                        )->where([
                            'id' =>$val['all_id']
                        ])->first();

                    }elseif($val['type'] ==3){
                        $info = MaterielModel::select(
                            'in_storage_status as out_status',
                            'pay_status',
                            'final_money',
                            'other_charges',
                            'fact_money as real_money',
                        )->where([
                            'id' =>$val['all_id']
                        ])->first();
                    }elseif($val['type'] == 4){
                        $info = BarterModel::select(
                            'out_status',
                            'pay_status',
                            'spread_price',
                            'barter_return_no',
                            'other_charges'
                        )->where([
                            'id' => $val['all_id'],
                            'delete_flag' => 0,
                        ])->first();
                        $val['spread_price'] = $info['spread_price']??0;
                        $returnInfo = SalesReturnModel::select('a.id','a.out_status')
                        ->from('sales_return as a')
                        ->leftJoin('check as b','a.id','=','b.all_id')
                        ->where([
                            'a.barter_return_no' => $info['barter_return_no']??'',
                            'b.type' => 5,
                        ])->first();
                        $val['return_in_status'] = $returnInfo['out_status']??'';
                    }
                    if(!empty($info)){
                        if($info['out_status'] ==2){
                            $val['out_in_status'] = 0;
                        }elseif($info['out_status'] ==1){
                            $val['out_in_status'] = 1;
                        }
                    }
                    $val['pay_status'] = $info['pay_status']??0;
                    $val['final_money'] = $info['final_money']??0;
                    $val['other_charges'] = $info['other_charges']??0;
                    $val['real_money'] = $info['real_money']??0;
                }
            }
        }
        return $this->success($model);
    }

    /**
     * 报溢报损同意或拒绝
     * change 在 2021/11/9 16:33 创建
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function agreeOrRefund1(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->except('role_id'), [
            'id' =>'required|integer',//审批主键id
            'all_id' =>'required|integer',//关联id
            'status' =>'required|string',//审批状态：0-拒绝 1-同意
            'remark' =>'string',//备注
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        //开启事务
        DB::beginTransaction();
        try{
            DB::enableQueryLog();
            $overflowBreakageChecksModel = OverflowBreakageChecksModel::where([
                'o_b_main_id'=>$data['all_id'],'admin_id'=>$this->getUserId()
            ])->first();

            if(empty($overflowBreakageChecksModel)) {
                throw new Exception('无此单据数据，请刷新后重试');
            }

            if($data['status']==1){
                //更新审核人审核状态
                $overflowBreakageChecksModel->status = 1;

                $overflowBreakageChecksModel->save();

                $all = OverflowBreakageChecksModel::where(['o_b_main_id'=>$data['all_id']])->count();
                $agree = OverflowBreakageChecksModel::where(['status'=>1,'o_b_main_id'=>$data['all_id']])->count();
                $refund = OverflowBreakageChecksModel::where(['status'=>2,'o_b_main_id'=>$data['all_id']])->count();

                if($all==$agree){//全部通过入库
                    $mainInfo = OverflowBreakageModel::where('id',$data['all_id'])->first();//主单信息
                    OverflowBreakageModel::where('id',$data['all_id'])->update(['status'=>1]);//更新报溢报损审核状态
                    CheckModel::where('id',$data['id'])->update(['status'=>1]);//审批状态更新
                    //出入库参数
                    $paramsArr = [];//出入库参数
                    $paramsArr['all_id'] = $data['all_id'];
                    $paramsArr['remark'] = '';
                    $paramsArr['all_id_type'] = 1;//报溢报损均为1
                    $OverflowBreakageDetailModel = OverflowBreakageDetailModel::where('o_b_main_id',$data['all_id'])->get()->toArray();

                    if(!empty($OverflowBreakageDetailModel)) {
                        foreach ($OverflowBreakageDetailModel as $k=>$val){
                            $paramsArr['content'][$k]['name'] = $val['name'];
                            $paramsArr['content'][$k]['price'] = 0;
                            $paramsArr['content'][$k]['type_name'] = $val['type_name'];
                            $paramsArr['content'][$k]['num'] = $val['num'];
                            $paramsArr['content'][$k]['warehouse'] = $val['warehouse'];
                            $paramsArr['content'][$k]['warehouse_id'] = $val['warehouse_id'];
                            $paramsArr['content'][$k]['shelf_id'] = $val['shelf_id'];
                            $paramsArr['content'][$k]['shelf_location_id'] = $val['shelf_location_id'];
                            $paramsArr['content'][$k]['serial_number'] = $val['serial_number'];
                            $paramsArr['content'][$k]['batch_info'] = $val['batch_info'];
                        }
                    }
                    else {
                        $paramsArr['content'] = '';
                    }

                    if($mainInfo['type']) {
                        $overflowBreakagePackageInfo = OverflowBreakagePackageModel::select(
                            'a.*',
                            'b.package_name'
                        )
                            ->from('overflow_breakage_package as a')
                            ->leftJoin('package as b', 'b.id', '=', 'a.package_id')
                            ->with('packageContent', function($query) {
                                $query->select(
                                    'overflow_breakage_package_content.*',
                                    'a.storage_name',
                                    'a.storage_address',
                                    'b.materiel_name',
                                    'b.is_use_serial',
                                    'b.type_name',
                                    'b.materiel_no',
                                    'overflow_breakage_package_content.shelf_id',
                                    'overflow_breakage_package_content.shelf_location_id',
                                    'c.id as materiel_class_id',
                                    'c.class_name as materiel_class_name',
                                    'c.class_no as materiel_class_no',
                                    'in_storage_num',
                                    'alert_num',
                                    'virtual_storage_num',
                                    'serial_number',
                                    'batch_info'
                                )
                                    ->leftJoin('storage as a', 'a.id', '=', 'overflow_breakage_package_content.storage_id')
                                    ->leftJoin('materiel_type as b', 'b.id', '=', 'overflow_breakage_package_content.type_id')
                                    ->leftJoin('materiel_class as c', 'c.id', '=', 'b.materiel_class_id')
                                    ->leftJoin('storage_manage as d', 'd.id', '=', 'overflow_breakage_package_content.storage_manage_id');
                            })
                            ->where('o_b_main_id',$data['all_id'])
                            ->get()->toArray();
                    }
                    else {
                        $overflowBreakagePackageInfo = [];
                    }

                    $checkModel = CheckModel::find($data['id']);
                    if($checkModel->type==0){//报溢入库
                        $paramsArr['in_storage_time'] = date('Y-m-d H:i:s');
                        $res = StorageManageService::inStorage(
                            $this->isUseShelf(),
                            $this->getUserId(),
                            $this->getMainUserId(),
                            $paramsArr,
                            $this->batchTitle()
                        );
                        if($res['code']){
                            throw new Exception($res['msg']);
                        }

                    }else{//报损出库
                        $paramsArr['out_storage_time'] = date('Y-m-d H:i:s');
                        $res = StorageManageService::checkOutStorage(
                            $this->isUseShelf(),
                            $this->getUserId(),
                            $this->getMainUserId(),
                            $paramsArr,
                            $data['all_id'],
                            $overflowBreakagePackageInfo,
                        );
                        if($res['code']){
                            throw new Exception($res['msg']);
                        }
                    }
                }
                if($all==($agree+$refund) && $refund){//部分拒绝
                    OverflowBreakageModel::where('id',$data['all_id'])->update(['status'=>2]);//更新报溢报损审核状态
                    CheckModel::where('id',$data['id'])->update(['status'=>1]);//审批状态更新
                }
            }else{//拒绝
                //更新审核人审核状态
                $overflowBreakageChecksModel->status = 2;
                $overflowBreakageChecksModel->refund_remark = isset($data['remark'])?$data['remark']:"";
                $overflowBreakageChecksModel->save();
                $obc = OverflowBreakageChecksModel::where(['status'=>0,'o_b_main_id'=>$data['all_id']])->first();
                if(!$obc){
                    OverflowBreakageModel::where('id',$data['all_id'])->update(['status'=>2]);//更新报溢报损审核状态
                    CheckModel::where('id',$data['id'])->update(['status'=>1]);//审批状态更新
                }
            }
            //更新临时审批人
            $model = CheckModel::where('id',$data['id'])->first();
            if($model['check_person_tmp']){
                $arr = explode(',',$model['check_person_tmp']);
                $userIdIndex = array_search($this->getUserId(),$arr);
                unset($arr[$userIdIndex]);
                $model->check_person_tmp = implode(',',$arr);
                $model->save();
            }
            DB::commit();//提交事务
            return $this->success();
        }catch (Exception $e){
            DB::rollBack();//事务回滚
            Log::debug('审批异常'.var_export($e->getMessage(), true));
            //异常响应
            return $this->fail('','审核报溢或报损失败');
        }
    }
}
